import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/utils/list_to_map_utils.dart';
import 'package:finance_app/src/utils/reg_exp_utils.dart';

mixin FormatGroupMapLocalMixin<T> {
  Map<String, List<T>> groupMap = {};

  // 排序方法
  void sortGroupToMap(List<T> list,
      {int sort(T a, T b),
      String group(T a),
      bool filter(T a),
      bool itemBefore(Map<String, List<T>> a, T b)}) {
    if (sort != null) list.sort(sort);
    for (final item in list) {
      if (filter == null || (filter != null && filter(item))) {
        if (itemBefore != null) {
          bool isSuccess = itemBefore(groupMap, item);
          if (isSuccess == true) {
            continue;
          }
        }
        final firstName = group(item);
        if (groupMap[firstName] == null) {
          groupMap[firstName] = [item];
        } else {
          groupMap[firstName].add(item);
        }
      }
    }
  }

  int sortIssuesAt(T a, T b, String getIssuedAt(T t), int getId(T t)) =>
      ListToMapUtils.sortIssuesAt<T>(a, b, getIssuedAt, getId);

  int sortPayAmount(T a, T b, int getFavorite(T t), num getAmount(T t)) =>
      ListToMapUtils.sortPayAmount<T>(a, b, getFavorite, getAmount);

  int sortNameFirst(T a, T b, String getName(T t)) =>
      ListToMapUtils.sortNameFirst<T>(a, b, getName);

  int sortName(T a, T b, String getName(T t)) =>
      ListToMapUtils.sortName<T>(a, b, getName);

  String groupFirstName(T a, String getName(T t), [String other = '']) =>
      ListToMapUtils.groupFirstName<T>(a, getName, other);

  String groupMonth(T a, String getTimeAt(T t)) =>
      ListToMapUtils.groupMonth<T>(a, getTimeAt);

  String groupOnly(T a) => '';

  bool favoriteBefore(Map<String, List<T>> map, T b, int getFavorite(T b)) =>
      ListToMapUtils.favoriteBefore<T>(map, b, getFavorite);

  bool meBefore(Map<String, List<T>> map, T b, int getId(T b)) {
    if (map['Me'] == null) {
      map['Me'] = [];
    }
    if (getId(b) == Config.userProfile.id) {
      map['Me'].add(b);
      return true;
    }
    return false;
  }

  bool onFilterSearch(String search, String name) {
    return RegExpUtils.getSearchRegExp(search).hasMatch(name ?? '');
  }
}
